package com.jiantong.work.impl.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import com.jiantong.user.impl.dao.ButcherFactoryDao;
import com.jiantong.user.model.ButcherFactory;
import com.jiantong.work.enums.PrintRelativeInfo;
import com.jiantong.work.impl.dao.CertNumberDao;
import com.jiantong.work.impl.dao.IssuanceTableDao;
import com.jiantong.work.model.ButcherReport;
import com.jiantong.work.model.ButcherReportSurveyRecord;
import com.jiantong.work.model.CertNumber;
import com.jiantong.work.model.IssuanceTable;
import com.jiantong.work.service.CreditProductService;
import com.jiantong.work.util.CertificateUtil;
import io.terminus.boot.rpc.common.annotation.RpcProvider;
import io.terminus.common.model.Response;
import io.terminus.common.utils.JsonMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * Created by maowenjie on 2017/5/11.
 */
@Slf4j
@Service
@RpcProvider
public class CreditProductServiceImpl implements CreditProductService {
    private static final String ZZLX = "4";                                                                                              //2:A证,4:B证
    private static final String JYLX = "1";
    private static final String FLAG = "DONG_YANG";
    private static final String COMMAND = "44";
    private static final String SERVICE = "4";
    private static final String USER_ID = "28540";
    private static final String CREDENTIAL_URL = "http://114.215.249.190:8080/app/app?";
    private static final String TARGET = "东阳市";

    //用dao层 来实现breedFactoryReadService的功能
    private final ButcherFactoryDao  butcherFactoryDao;
    private final IssuanceTableDao issuanceTableDao;
    private final CertNumberDao certNumberDao;

    @Autowired
    public CreditProductServiceImpl( ButcherFactoryDao  butcherFactoryDao, IssuanceTableDao issuanceTableDao, CertNumberDao certNumberDao) {
        this.butcherFactoryDao = butcherFactoryDao;
        this.issuanceTableDao = issuanceTableDao;
        this.certNumberDao = certNumberDao;
    }
    private static final ObjectMapper objectMapper = JsonMapper.nonEmptyMapper().getMapper();


    @Override
    public Response<IssuanceTable> isSucceed (ButcherReport butcherReport, ButcherReportSurveyRecord butcherReportSurveyRecord) {
        Long id = butcherReport.getButcherFactoryId();
        ButcherFactory butcherFactory =butcherFactoryDao.findById(id);
        CertNumber certNumber = certNumberDao.randomFind();
        if (certNumber == null){
            log.error("开证编号读取失败,请检查是否号段已用完");
            return Response.fail("号段读取失败!");
        }
        String jyhgzmbh=certNumber.getCertNumber();                                                             //产品AB证编号// 表需要加字段
        String hzName=butcherReport.getOwner();                                                                        //货主-名称
        String hzLxdh="1880008888";      //TODO                         // 需要添加  货主联系电话  butcherReport.getOwnerMobile()
//        String hzLxdh= butcherReport.getHzLxdh()+"";
        String productTypeId= CertificateUtil.unitKind(butcherReport.getProductType())+"";  //产品种类id
        String sl=butcherReportSurveyRecord.getSyncQualifiedQuantity() * 90 + "";                                        //开证数量productType
        String ggdw=CertificateUtil.unitShift(CertificateUtil.PRODUCT_UNIT)+"";                                                                   //规格单位id
        String animalTypeId = CertificateUtil.kind(butcherReport.getProductType())+"";
        String scdwName = butcherReport.getSourceName();                                                                                    //  生产单位-名称  来源名称 养殖场名字   butcherReport.getSourceName()
//        String scdwRegionId="0591";                                                                                                        // 生产单位--地区id  养殖场id  butcherReport.getSourceId()
        String scdwRegionId = "0000";      //TODO
        if(butcherReport.getSourceId() != null){
            scdwRegionId = butcherReport.getSourceId() + "";
        }
        while (scdwRegionId.length() < 12){
            scdwRegionId = scdwRegionId +"0";
        }
//       "生产单位详细地址, 即屠宰场详细地址"                                                                     // 生产单位-详细地址 即屠宰场详细地址
        String scdwXxdz = butcherFactory.getName() + " , " + butcherFactory.getDetail();                                                                                           // 生产单位-详细地址 即屠宰场详细地址
        String cdRegionId=butcherFactory.getAreaCode();//TODO 区号                                                                                    //场地地区id 屠宰场
        while (cdRegionId.length() < 12){
            cdRegionId = cdRegionId +"0";
        }
        String cdXxdz = TARGET;    //需要添加字段 产地详细地址,养殖场详细地址

//        String cdXxdz= butcherReport.getCdXxdz();
        String mddRegionId="057900000000";  //todo 目的地-地区id
//        String mddRegionId = butcherReport.getMddRegionId();
        while (mddRegionId.length() < 12){
            mddRegionId = mddRegionId +"0";
        }
        String mddXxdz = butcherFactory.getName() + " , " + butcherFactory.getDetail();                                                                        //添加字段,目的地详细地址即产品卖往的地址,  目前先规定为屠宰场的详细地址
        String jybsh=butcherFactory.getIdentificationNumber();                                                                                                           //检疫标识号
        String qfsj=new SimpleDateFormat("yyyy-MM-dd%20HH:mm:ss").format(new Date());                                                                       //签发时间
        String isAllFinished="1";                                                                                                                                       //添加字段   检疫合格数量是否以开完1-是  0-否
        String sbztRegionId="057000000000";    //todo 目的地-地区id            // 添加字段  申报主体所在地区-货主所地区id  即养殖场地区id
//        String sbztRegionId = butcherReport.getSbztRegionId();
        while (sbztRegionId.length() < 12){
            sbztRegionId = sbztRegionId +"0";
        }
        String qfUserName=butcherReportSurveyRecord.getSurveyUserName();                                                                                                       //签发人名称  survey_user_name

        Map<String,String> maps = Maps.newHashMap();
        maps.put("zzlx",ZZLX);
        maps.put("jylx",JYLX);
        maps.put("flag",FLAG);
        maps.put("command",COMMAND);
        maps.put("service",SERVICE);
        maps.put("userid",USER_ID);
        maps.put("jyhgzmbh",jyhgzmbh);
        maps.put("hzName",hzName);
        maps.put("hzLxdh",hzLxdh);
        maps.put("productTypeId",productTypeId);
        maps.put("sl",sl);
        maps.put("ggdw",ggdw);
        maps.put("animalTypeId",animalTypeId);
        maps.put("scdwName",scdwName);
        maps.put("scdwRegionId",scdwRegionId);
        maps.put("scdwXxdz",scdwXxdz);
        maps.put("cdRegionId",cdRegionId);
        maps.put("cdXxdz",cdXxdz);
        maps.put("mddRegionId",mddRegionId);
        maps.put("mddXxdz",mddXxdz);
        maps.put("jybsh",jybsh);
        maps.put("qfsj",qfsj);
        maps.put("isAllFinished",isAllFinished);
        maps.put("sbztRegionId",sbztRegionId);
        maps.put("qfUserName",qfUserName);

        String credential_url = CREDENTIAL_URL;

        for (String key : maps.keySet()) {
            credential_url += key+"="+maps.get(key)+"&";
        }
        //根据查出来的参数, 组成一个get请求的URL
        try {
            URL url = new URL(credential_url);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            int code = connection.getResponseCode();
            if (code != 200) {
                log.error("发生其它错误，认证服务器返回"+ code);
                return Response.fail(code + "错误");
            }
            InputStream is = connection.getInputStream();
            byte[] response = new  byte[is.available()];
            is.read(response);
            is.close();
            if (response.length == PrintRelativeInfo.HTTP_FAILED_RESULT_STATUS.value()) {
//                certNumber.setCertStatus(1);
//                certNumberDao.update(certNumber);
                log.error("认证无效，找不到此次认证的会话信息！");
                return Response.fail("认证无效，找不到此次认证的会话信息！");
            }
            String userId = new String(response, "UTF-8");
            Map<String , String> resultMap = objectMapper.readValue(userId, new TypeReference<Map<String , String>>(){});
            String result_code = resultMap.get("code"); //  0 为失败; 1 为成功

            //判断是否成功, 成功改变isSucceed为true
            if (result_code.equals("0")){
                log.error("认证无效，找不到此次认证的会话信息！");
                return Response.fail("认证无效，找不到此次认证的会话信息！");
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
            return Response.fail("认证失败!");
        } catch (Exception e) {
            e.printStackTrace();
            return Response.fail("认证失败！");
        }
        //写入打印表,
        IssuanceTable issuanceTable = new IssuanceTable();

        issuanceTable.setZzlx(ZZLX);
        issuanceTable.setCommand(COMMAND);
        issuanceTable.setFlag(FLAG);
        issuanceTable.setGgdw(ggdw);
        issuanceTable.setHzLxdh(hzLxdh);
        issuanceTable.setHzName(hzName);
        issuanceTable.setJyhgzmbh(jyhgzmbh);
        issuanceTable.setJylx(JYLX);
        issuanceTable.setMddRegionId(mddRegionId);
        issuanceTable.setMddXxdz(mddXxdz);
        issuanceTable.setAnimalTypeId(animalTypeId);
        issuanceTable.setQfsj(qfsj);
        issuanceTable.setQfUserName(qfUserName);
        issuanceTable.setSbztRegionId(sbztRegionId);
        issuanceTable.setService(SERVICE);
        issuanceTable.setSl(sl);
        issuanceTable.setUserId(USER_ID);
        issuanceTable.setCdRegionId(cdRegionId);
        issuanceTable.setCdXxdz(cdXxdz);
        issuanceTable.setScdwName(scdwName);
        issuanceTable.setScdwXxdz(scdwXxdz);
        issuanceTable.setScdwRegionId(scdwRegionId);
        issuanceTable.setIsAllFinished(isAllFinished);
        issuanceTable.setJybsh(jybsh);
        issuanceTable.setProductTypeId(productTypeId);
        //额外添加的字段
        issuanceTable.setReportId(butcherReport.getId());
        issuanceTable.setQfUserId(butcherReportSurveyRecord.getVetUserId());
        issuanceTable.setProductType(CertificateUtil.unitKindName(butcherReport.getProductType()));
        issuanceTable.setGgdwName(CertificateUtil.unitShiftName(CertificateUtil.PRODUCT_UNIT));        //单位 例：只
        issuanceTable.setCertStatus(PrintRelativeInfo.PRINT_UNUSED_STATUS.value());

        Boolean is_succeed = issuanceTableDao.create(issuanceTable);

        if (!is_succeed){
            return Response.fail("写入打印表出错");
        }
        //发证成功改编号状态应该改为1
        certNumber.setCertStatus(PrintRelativeInfo.CERT_USED_STATUS.value());
        certNumberDao.update(certNumber);
//        issuanceTable.setCreatedAt(new Date());   --todo
        return Response.ok(issuanceTable); //返回一个打印表实体类对象    -- todo 加一个manager
    }
}
